// DOM元素
const momentsList = document.getElementById('momentsList');
const commentInputContainer = document.getElementById('commentInputContainer');
const commentInput = document.getElementById('commentInput');
const submitComment = document.getElementById('submitComment');
const postBtn = document.querySelector('.post-btn');

// 当前正在评论的动态ID
let currentMomentId = null;

// 初始化朋友圈
async function initMoments() {
    //获取
    //发送请求
    const data = await fetch('http://localhost/api/note/getMoments', {
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data.data;
        }
        )
        .catch(error => console.error('Error:', error));
    momentsData = data;

    renderMoments();

    // 发布按钮点击事件
    postBtn.addEventListener('click', function () {
        alert('发布功能正在开发中...');
    });
}

// 渲染朋友圈动态
function renderMoments() {
    momentsList.innerHTML = '';

    momentsData.forEach(moment => {
        const momentElement = createMomentElement(moment);
        momentsList.appendChild(momentElement);
    });
}

// 创建单个动态元素
function createMomentElement(moment) {
    const momentItem = document.createElement('div');
    momentItem.className = 'moment-item';
    momentItem.dataset.id = moment.id;

    // 用户信息
    let userInfoHTML = `
        <div class="user-info">
            <img src="${moment.user.avatar}" alt="${moment.user.name}" class="avatar">
            <span class="user-name">${moment.user.name}</span>
        </div>
        <div class="moment-content">
    `;

    //标题
    if (moment.title) {
        userInfoHTML += `<h1 class="moment-text">${moment.title}</h1>`;
    }

    // 动态内容
    if (moment.content) {
        userInfoHTML += `<p class="moment-text">${moment.content}</p>`;
    }

    // 动态图片
    if (moment.images && moment.images.length > 0) {
        userInfoHTML += `<div class="moment-images">`;

        moment.images.forEach((image, index) => {
            const imageClass = moment.images.length === 1 ? 'moment-image single-image' : 'moment-image';
            userInfoHTML += `<img src="${image}" alt="动态图片${index + 1}" class="${imageClass}">`;
        });

        userInfoHTML += `</div>`;
    }

    userInfoHTML += `</div>`;

    // 时间和操作按钮
    let actionsHTML = `
        <div class="moment-time">${moment.time}</div>
        <div class="moment-actions">
            <button class="action-btn like-btn" data-moment-id="${moment.id}">
                <i>${moment.isLiked ? '♥' : '♡'}</i> 赞
            </button>
            <button class="action-btn comment-btn" data-moment-id="${moment.id}">
                <i>💬</i> 评论
            </button>
        </div>
    `;

    // 点赞和评论区域
    let interactionHTML = '';
    if (moment.likes != null && (moment.likes.length > 0 || moment.comments.length > 0)) {
        interactionHTML += `<div class="moment-interaction">`;

        // 点赞列表
        if (moment.likes.length > 0) {
            interactionHTML += `<div class="like-list">♥ ${moment.likes.join('、')}</div>`;
        }

        // 评论列表
        if (moment.comments != null && moment.comments.length > 0) {
            interactionHTML += `<div class="comment-list">`;
            moment.comments.forEach(comment => {
                interactionHTML += `
                    <div class="comment-item">
                        <span class="comment-user">${comment.username}：</span>
                        ${comment.content}
                    </div>
                `;
            });
            interactionHTML += `</div>`;
        }

        interactionHTML += `</div>`;
    }

    momentItem.innerHTML = userInfoHTML + actionsHTML + interactionHTML;

    // 添加事件监听器
    const likeBtn = momentItem.querySelector('.like-btn');
    const commentBtn = momentItem.querySelector('.comment-btn');

    likeBtn.addEventListener('click', () => toggleLike(moment.id));
    commentBtn.addEventListener('click', () => showCommentInput(moment.id));

    return momentItem;
}

// 点赞/取消点赞
async function toggleLike(momentId) {

    //查询是否点赞过
    const data = await fetch(`http://localhost/api/note/liked?noteId=${momentId}`, {
        mode: 'cors', // 明确请求模式
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data;
        }
        )
        .catch(error => console.error('Error:', error));
    initMoments();

    // const moment = momentsData.find(m => m.id === momentId);
    // if (!moment) return;

    // moment.isLiked = !moment.isLiked;

    // if (moment.isLiked) {
    //     // 如果还没点赞，添加当前用户到点赞列表
    //     if (!moment.likes.includes(currentUser.name)) {
    //         moment.likes.push(currentUser.name);
    //     }
    // } else {
    //     // 取消点赞，从点赞列表中移除
    //     moment.likes = moment.likes.filter(name => name !== currentUser.name);
    // }

    // 重新渲染该动态
    // const momentElement = document.querySelector(`.moment-item[data-id="${momentId}"]`);
    // if (momentElement) {
    //     const newMomentElement = createMomentElement(moment);
    //     momentElement.replaceWith(newMomentElement);
    // }
}

// 显示评论输入框
function showCommentInput(momentId) {
    currentMomentId = momentId;
    commentInputContainer.style.display = 'flex';
    commentInput.focus();
}

// 提交评论
submitComment.addEventListener('click', async function () {
    const commentText = commentInput.value.trim();
    if (!commentText || !currentMomentId) return;

    const moment = momentsData.find(m => m.id === currentMomentId);
    //评论
    // http://localhost:8080/api/note/sentMessage?noteId=9&mes=真好看啊
    // const data = await fetch(`http://localhost/api/note/liked?noteId=${momentId}`, {
    const data = await fetch(`http://localhost/api/note/sentMessage?noteId=${currentMomentId}&mes=${commentText}`, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data;
        }
        )
        .catch(error => console.error('Error:', error));
    // let moment = data;

    initMoments();

    // if (moment) {
    //     moment.comments.push({
    //         user: currentUser.name,
    //         content: commentText
    //     });

    //     // 重新渲染该动态
    //     const momentElement = document.querySelector(`.moment-item[data-id="${currentMomentId}"]`);
    //     if (momentElement) {
    //         const newMomentElement = createMomentElement(moment);
    //         momentElement.replaceWith(newMomentElement);
    //     }
    // }

    // 重置评论输入
    commentInput.value = '';
    commentInputContainer.style.display = 'none';
    currentMomentId = null;
});

// 点击输入框外部隐藏评论框
document.addEventListener('click', function (e) {
    if (!commentInputContainer.contains(e.target) &&
        !e.target.classList.contains('comment-btn')) {
        commentInputContainer.style.display = 'none';
    }
});

// 初始化朋友圈
initMoments();